﻿using System;
using System.Linq;
using System.ComponentModel;
using System.Windows.Data;
using System.Collections.ObjectModel;

using Microsoft.Practices.Prism.ViewModel;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Regions;

using SystemModule.Models;
using SystemModule.Services;
using ServiceAgent;
using Infrastructure;
using Infrastructure.Helpers;
using Infrastructure.Events;
using System.Windows.Input;
using System.Windows;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Prism.Interactivity.InteractionRequest;
using SystemModule.Views;
using ServiceAgent.StudentService;
using System.Collections.Generic;
using ServiceAgent.SystemService;

namespace SystemModule.ViewModels
{
    /// <summary>
    /// ViewModel for NguoiDungDetailViewModel.
    /// </summary>
    public class NguoiDungDetailViewModel : NotificationObject, INavigationAware
    {
        #region Fields
        private IRegionNavigationService navigationService;
        private IEventAggregator eventAggregator;

        private readonly IUnityContainer container;
        private IRegionManager regionManager;

        int uid;

        UserDTO user;

        ObservableCollection<DonViDTO> donViList;
        ObservableCollection<DonViDTO> donViUserList = new ObservableCollection<DonViDTO>();
        private ObservableCollection<DonViDTO> oldDonViUserList;
        

        #endregion

        #region Constructor
        /// <summary>
        /// Default constructor.
        /// </summary>
        public NguoiDungDetailViewModel(IEventAggregator eventAggregator, IRegionManager regionManager, IUnityContainer container)
        {
            this.eventAggregator = eventAggregator;
            this.regionManager = regionManager;
            this.container = container;

            this.Initialize();
        }
        #endregion

        #region Administrative Properties
        public UserDTO User
        {
            get { return user; }
            set
            {
                user = value;
                RaisePropertyChanged(() => this.User);
                this.SaveCommand.RaiseCanExecuteChanged();
            }
        }

        public ObservableCollection<DonViDTO> DonViList
        {
            get { return donViList; }
            set
            {
                donViList = value;
                RaisePropertyChanged(() => this.DonViList);
            }
        }

        public ObservableCollection<DonViDTO> DonViUserList
        {
            get { return donViUserList; }
            set
            {
                donViUserList = value;
                RaisePropertyChanged(() => this.DonViUserList);
            }
        }
        #endregion

        #region Command Properties
        public DelegateCommand<object> GoBackCommand { get; private set; }
        public DelegateCommand SaveCommand { get; private set; }
        #endregion

        #region Private Methods
        private void Initialize()
        {
            this.GoBackCommand = new DelegateCommand<object>(GoBack, CanGoBack);
            this.SaveCommand = new DelegateCommand(this.OnRaiseSave);
        }

        void GetUser(int id)
        {
            try
            {
                using (var proxy = container.Resolve<SystemServiceAgent>())
                {
                    User = proxy.GetUserByID(id);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Có lỗi xảy ra");
            }
        }

        void GetDonViList(int id)
        {
            try
            {
                using (var proxy = container.Resolve<SystemServiceAgent>())
                {
                    DonViList = proxy.GetDonViNotYetByUserID(id);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Có lỗi xảy ra");
            }
        }

        void GetDonViUserList(int id)
        {
            try
            {
                using (var proxy = container.Resolve<SystemServiceAgent>())
                {
                    oldDonViUserList = proxy.GetDonViByUserID(id);
                }
                foreach (var donvi in oldDonViUserList)
                {
                    donViUserList.Add(donvi);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Có lỗi xảy ra");
            }
        }

        private void OnRaiseSave()
        {
            try
            {

                using (var proxy = container.Resolve<SystemServiceAgent>())
                {
                    if (!String.IsNullOrEmpty(User.TenTaiKhoan))
                    {
                        proxy.SaveUser(User);
                    }
                    else { throw new ArgumentException(null, "TaiKhoan"); }
                }

                var toRemove = oldDonViUserList.Except(donViUserList);
                var toAdd = donViUserList.Except(oldDonViUserList);

                if (toAdd.Count() > 0)
                {
                    using (var proxy = container.Resolve<SystemServiceAgent>())
                    {
                        proxy.SetDonViListForUser(uid, new ObservableCollection<DonViDTO>(toAdd));
                    }
                }

                if (toRemove.Count() > 0)
                {
                    using (var proxy = container.Resolve<SystemServiceAgent>())
                    {
                        proxy.UnSetDonViListForUser(uid, new ObservableCollection<DonViDTO>(toRemove));
                    }
                }
                oldDonViUserList = donViUserList;
                MessageBox.Show("Lưu lại thành công");
            }
            catch (ArgumentException e)
            {
                if (e.ParamName == "TaiKhoan")
                {
                    MessageBox.Show("Tên tài khoản không hợp lệ",
                    "Lỗi", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }

            catch (Exception)
            {
                MessageBox.Show("Có lỗi xảy ra");
            }
        }

        private bool CanRaiseSave()
        {
            return !string.IsNullOrWhiteSpace(this.User.TenTaiKhoan);
        }


        //private void OnRaiseSave()
        //{
        //    try
        //    {
        //        using (var proxy = container.Resolve<CatalogueServiceAgent>())
        //        {
        //            proxy.SaveDonVi(DonVi);
        //        }

        //        var toRemove = oldQuyenDonViList.Except(quyenDonViList);
        //        var toAdd = quyenDonViList.Except(oldQuyenDonViList);

        //        if (toAdd.Count() > 0)
        //        {
        //            using (var proxy = container.Resolve<SystemServiceAgent>())
        //            {
        //                proxy.SetQuyenListForDonVi(uid, new ObservableCollection<QuyenDTO>(toAdd));
        //            }
        //        }

        //        if (toRemove.Count() > 0)
        //        {
        //            using (var proxy = container.Resolve<SystemServiceAgent>())
        //            {
        //                proxy.UnSetQuyenListForDonVi(uid, new ObservableCollection<QuyenDTO>(toRemove));
        //            }
        //        }
        //    }
        //    catch (Exception)
        //    {
        //    }
        //}

        private void GoBack(object commandArg)
        {
            if (navigationService.Journal.CanGoBack)
            {
                navigationService.Journal.GoBack();
            }
        }

        private bool CanGoBack(object commandArg)
        {
            return navigationService.Journal.CanGoBack;
        }
        #endregion

        #region INavigationAware Members
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            // Called to see if this view can handle the navigation request.
            // If it can, this view is activated.
            return false;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

            // Called when this view is deactivated as a result of navigation to another view.
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            //// Called to initialize this view during navigation.

            // getting a reference to navigation service:
            if (navigationService == null)
                navigationService = navigationContext.NavigationService;

            //// Retrieve any required paramaters from the navigation Uri.
            string id = navigationContext.Parameters["ID"];
            if (!string.IsNullOrEmpty(id))
            {
                this.uid = Convert.ToInt32(id);
            }
            this.GetUser(uid);
            this.GetDonViList(uid);
            this.GetDonViUserList(uid);
        }
        #endregion
    }
}
